package com.haoshui.service.impl;

import com.haoshui.constants.RedisCacheConstans;
import com.haoshui.domain.ResponseResult;
import com.haoshui.domain.entity.LoginUser;
import com.haoshui.domain.entity.User;
import com.haoshui.domain.vo.BlogUserLoginVo;
import com.haoshui.domain.vo.UserInfoVo;
import com.haoshui.enums.AppHttpCodeEnum;
import com.haoshui.service.BlogLoginService;
import com.haoshui.utils.BeanCopyUitls;
import com.haoshui.utils.JwtUtil;
import com.haoshui.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
         Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //判读是不是有用户
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户登陆失败");
        }

        //获取userId，生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //把用户存入redis
        redisCache.setCacheObject(RedisCacheConstans.BOLG_LOGIN_USER_KEY +userId, loginUser);

        //封装到vo
        UserInfoVo userInfoVo = BeanCopyUitls.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt, userInfoVo);

        return ResponseResult.okResult(blogUserLoginVo);
    }

    @Override
    public ResponseResult logout() {
        //获取用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //获得userID
        Long id = loginUser.getUser().getId();

        boolean b = redisCache.deleteObject(RedisCacheConstans.BOLG_LOGIN_USER_KEY + id);
        ResponseResult result = null;
        if(b){
            //删除成功
            result = ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        }else{
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
        }
        return result;
    }
}
